package com.whereta.aop;

import com.alibaba.fastjson.JSON;
import com.whereta.common.HtmlObjUtil;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by vincent on 15-9-23.
 */
@Aspect
@Component
public class ServiceLogAop {

    private static final Logger loggerRecord = Logger.getLogger("RECORD");


    @Around("execution(public * com.whereta.service.*.*(..))")
    public Object serviceAOP(ProceedingJoinPoint point) throws IOException {
        Object proceed = null;
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Object target = point.getTarget();
        String className = target.getClass().getName();
        try {
            Object[] args = point.getArgs();

            Object o = HtmlObjUtil.replaceStringHtml(args);

            String jsonString = JSON.toJSONString(args);

            if (loggerRecord.isInfoEnabled()) {
                loggerRecord.info("Class:" + className + "  MethodName:" + method.getName() + "  Params:" + jsonString);
            }
            proceed = point.proceed((Object[]) o);
            String ReturnString = JSON.toJSONString(proceed);
            if (loggerRecord.isInfoEnabled()) {
                loggerRecord.info("ReturnMsg:<!--  Class:" + className + "  MethodName:" + method.getName() + "  Content: " + ReturnString + "  -->");
            }
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
        return proceed;
    }

}
